﻿using Newtonsoft.Json;
using PosClient.Helper;
using PosClient.Interfaces;
using PosClient.Job;
using PosClient.Model;
using PosClient.Service;
using ReactiveUI;
using Splat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;

namespace PosClient.ViewModel
{
    public class DownLoadViewModel: ReactiveObject
    {

        public BindingList<JobEntity> JobList
        {
            get => _JobList;
            set => this.RaiseAndSetIfChanged(ref _JobList, value);
        }
        private BindingList<JobEntity> _JobList = new BindingList<JobEntity>();

        public int Index
        {
            get => _Index;
            set => this.RaiseAndSetIfChanged(ref _Index, value);
        }
        private int _Index;

        public JobEntity SelectJob { get => JobList[Index]; }


        public ReactiveCommand<Unit, Unit> GetJobCommand { get; }

        public ReactiveCommand<string, Unit> RunJobCommand { get; }

        public DownLoadViewModel()
        { 
            GetJobCommand = ReactiveCommand.Create(GetJobCommandImpl);
            RunJobCommand = ReactiveCommand.Create<string>(RunJobCommandImpl);
        }

        private void GetJobCommandImpl()
        {
            JobList.Clear();
            using (var conn = FreeClient.Sqlite)
            {
                var jobs = conn.Select<JobEntity>().ToList();
                if (jobs.Count == 0)
                {
                    var redis = FreeClient.Redis;
                    var redisJob = redis.HGetAll(RedisKey.Redis_Job);
                    if (redisJob.Count > 0)
                    {
                        foreach (var jobredis in redisJob)
                        {
                            jobs.Add(JsonConvert.DeserializeObject<JobEntity>(jobredis.Value));
                        }
                    }
                }
                foreach (var job in jobs)
                {
                    JobList.Add(job);
                }
            }
        }

        private void RunJobCommandImpl(string jobname)
        {
            var jobs = Locator.Current.GetService<JobManager>();
            var job = JobList.Where(x => x.JobName == jobname).First();
            jobs.RunJob(job);
        }
    }
}
